package zw_1601_1700.zw_1658_将x减到0的最小操作数;

class Solution {
    public static void main(String[] args) {
        int[] nums = {3, 2, 20, 1, 1, 3};
        int x = 10;
        int operations = minOperations(nums, x);
        System.out.println(operations);
    }


    public static int minOperations(int[] nums, int x) {
        int sum = 0, left = 0, right = 0, maxLen = -1, count = 0;
        int n = nums.length;
        for (int num : nums) sum += num;
        int tar = sum - x;
        if (tar == 0) return n;
        if (tar < 0) return -1;
        while (right < n) {
            count += nums[right];
            while (count > tar) {
                count -= nums[left];
                left++;
            }
            if (tar == count) {
                maxLen = Math.max(maxLen, right - left + 1);
            }
            right++;
        }
        return maxLen < 0 ? -1 : n - maxLen;
    }
}